package com.ninetaildemonfox.zdl.socialproject;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.utils.map.BaseUrl;
import com.kongzue.baseokhttp.util.BaseOkHttp;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.takephoto.TakePhotoUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.mob.MobSDK;
import com.ninetaildemonfox.zdl.ninetaildemonfox.base.BaseApplication;
import com.ninetaildemonfox.zdl.socialproject.db.Myinfo;
import com.ninetaildemonfox.zdl.socialproject.db.UserDao;
import com.ninetaildemonfox.zdl.socialproject.huanxin.DemoHelper;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.main.DatingHallFragment;
import com.ninetaildemonfox.zdl.socialproject.utils.Constant;
import com.ninetaildemonfox.zdl.socialproject.utils.GlideImageLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

import static com.kongzue.dialog.util.DialogSettings.STYLE.STYLE_IOS;

/**
 * 创建人： Nine tails fox
 * 创建时间： 2019/7/15
 * 功能描述：程序主入口，当程序启动的时候，会调用这个方法
 * 联系方式：1037438704@qq.com
 *
 * @author NineTailDemonFox
 */

public class SpApplication extends BaseApplication {
    public static LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    public static String LATITUDE, LONGITUDE, CITY;

    public static SpApplication ourInstance;

    public static SpApplication getInstance() {
        return ourInstance;
    }

    public static Context appContext = null;

    @Override
    public void onCreate() {
        MultiDex.install(this);
        super.onCreate();
        DialogSettings.DEBUGMODE = true;
        appContext = this;
        ourInstance = this;
        BaseOkHttp.DEBUGMODE = true;
        BaseOkHttp.serviceUrl = BaseUrl.BaseHttpUrl;
        BaseOkHttp.TIME_OUT_DURATION = 30;
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        //初始化Toast
        ToastManager.instance.init(this);
        MobSDK.init(this);//mob平台

        xiangjiduihuakuang();
        huanxin();
        xiangce();
        map();
    }

    private void xiangjiduihuakuang() {
        DialogSettings.isUseBlur = true;                   //是否开启模糊效果，默认关闭
        DialogSettings.style = STYLE_IOS;          //全局主题风格，提供三种可选风格，STYLE_MATERIAL, STYLE_KONGZUE,
        //相机配置初始化
        TakePhotoUtil.ALLOW_MULTIPLE = false;                               //是否允许多选图片
        TakePhotoUtil.COMPRESSED_PICS = true;                               //是否开启压缩
        TakePhotoUtil.DEFAULT_QUALITY = 90;                                 //压缩框架：图片质量
        TakePhotoUtil.DEFAULT_MAX_WIDTH = 1080;                             //压缩框架：图片最大宽度
        TakePhotoUtil.DEFAULT_MAX_HEIGHT = 1080;                            //压缩框架：图片最大高度
        TakePhotoUtil.DEFAULT_PIC_TYPE = Bitmap.CompressFormat.JPEG;        //压缩框架：默认压缩格式
    }

    private void huanxin() {
        //init demo helper
        DemoHelper.getInstance().init(appContext);
        // 请确保环信SDK相关方法运行在主进程，子进程不会初始化环信SDK（该逻辑在EaseUI.java中）
        if (EaseUI.getInstance().isMainProcess(this)) {
        }
        initDbDao(this);
    }

    private UserDao userDao;

    private void initDbDao(Context context) {
        userDao = new UserDao(context);
    }

    private boolean sdkInited = false;

    public synchronized boolean initSDK(Context context, EMOptions options) {
        if (sdkInited) {
            return true;
        }
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);

        // 如果app启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process
        // name就立即返回
        if (processAppName == null || !processAppName.equalsIgnoreCase(appContext.getPackageName())) {

            // 则此application::onCreate 是被service 调用的，直接返回
            return false;
        }
        if (options == null) {
            EMClient.getInstance().init(context, initChatOptions());
        } else {
            EMClient.getInstance().init(context, options);
        }
        sdkInited = true;
        return true;
    }

    private EMOptions initChatOptions() {

        // 获取到EMChatOptions对象
        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(true);
        // 设置是否需要已读回执
        options.setRequireAck(true);
        // 设置是否需要已送达回执
        options.setRequireDeliveryAck(false);
        return options;
    }

    /**
     * check the application process name if process name is not qualified, then
     * we think it is a service process and we will not init SDK
     *
     * @param pID
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {

                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
            }
        }
        return processName;
    }

    private void xiangce() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
//        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    public enum ToastManager {
        instance;
        private TextView contentTextView;
        private Toast toast;

        public void init(Context context) {
            contentTextView = (TextView) LayoutInflater.from(context).inflate(R.layout.view_toast, null);
            toast = new Toast(context);
            toast.setView(contentTextView);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }

        public void show(CharSequence charSequence, int duration) {
            if (!TextUtils.isEmpty(charSequence)) {
                contentTextView.setText(charSequence);
                toast.setDuration(duration);
                toast.show();
            }
        }
    }


    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.home_bg, android.R.color.black);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    private void map() {
        mLocationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setAddrType("all");
        option.setOpenGps(true);
        option.setScanSpan(1000);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        option.setEnableSimulateGps(false);
        mLocationClient.registerLocationListener(myListener);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (CITY == null) {
                LATITUDE = location.getLatitude() + "";    //获取纬度信息
                LONGITUDE = location.getLongitude() + "";    //获取经度信息
                CITY = location.getCity();
                DatingHallFragment.city = location.getCity();
            } else {
                mLocationClient.stop();
            }
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private String username = "";
//    private Map<String, EaseUser> contactList;

    public String getCurrentUserName() {
        if (TextUtils.isEmpty(username)) {
            username = Myinfo.getInstance(ourInstance).getUserInfo(Constant.KEY_USERNAME);

        }
        return username;
    }
}
